package Tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class TcpServer {
    private ServerSocket serverSocket=null;
    public TcpServer(int port) throws IOException {
        serverSocket=new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务端上线了！");
        ExecutorService service= Executors.newCachedThreadPool();
        while(true)
        {
            Socket clientSocket=serverSocket.accept();
            service.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        proccessConnection(clientSocket);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }
    }
    public void proccessConnection(Socket clientSocket) throws IOException {
        //进入方法，先打印一个日志，表示当前有客户但上线了
        System.out.printf("[%s:%d] 客户端上线！\n",clientSocket.getInetAddress(),clientSocket.getPort() );
        //接下来进行信息交互
        try(InputStream inputStream=clientSocket.getInputStream())
        {
            OutputStream outputStream=clientSocket.getOutputStream();
            Scanner scanner = new Scanner(inputStream);
            while(true) {
                if (!scanner.hasNext())
                {
                    System.out.printf("[%s:%d] 客户端下线了\n",clientSocket.getInetAddress(),clientSocket.getPort());
                    break;
                }

                //1、请求并解析
                String request=scanner.next();
                //2、根据请求，计算响应
                String response=proccess(request);

                PrintWriter printWriter=new PrintWriter(outputStream);
                printWriter.println(response);
                //此处要记得刷新缓冲区，如果没有刷新操作，数据可能还在内存中，没有被写入网卡
                printWriter.flush();
                System.out.printf("[%s:%d] req=%s, resp=%s\n", clientSocket.getInetAddress(), clientSocket.getPort(),request, response);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        finally {
            clientSocket.close();
        }

    }
    public String proccess(String request)
    {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpServer tcpServer=new TcpServer(9090);
        tcpServer.start();
    }
}
